package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.jihuo.config.TaskManager;
import com.ruoyi.jihuo.domain.JhTmProductsOnSale;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class BatchProcessor {

    @Autowired
    private PriorityHandlerChain priorityHandlerChain;
    @Autowired
    private TaskManager taskManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 批量处理数据
     * 数据处理前会判断任务的状态
     */
    @Async("releaseATaskAnalysisExecutor")
    public CompletableFuture<List<JhTmProductsOnSale>> processBatch(List<JSONObject> dataList, String taskId) {
        List<JhTmProductsOnSale> productsOnSales = new ArrayList<>();

        for (JSONObject context : dataList) {
            if (taskManager.isCancelled(taskId)) {
                break; // 检查取消标记，立即中止
            }
            JhTmProductsOnSale productsOnSale = context.getObject("productsOnSale", JhTmProductsOnSale.class);
            try {
                priorityHandlerChain.handleRequest(new ProcessContext<>(context));
                if ("2".equals(productsOnSale.getJhStatus())) {
                    productsOnSale.setJhListingTime(new Date());
                    productsOnSale.setJhExplain("商品上架成功");
                }
            } catch (Exception e) {
                productsOnSale.setJhStatus("3");
                //处理底层异常
                String errorInfo = e.getMessage().replaceAll("java.lang.RuntimeException:","->");
                productsOnSale.setJhExplain("商品上架处理失败" + errorInfo);
                log.error("上架商品处理失败", e);
            }
            productsOnSales.add(productsOnSale);
            // 更新进度
            redisCache.setCacheMapValueIncrement((CacheConstants.TASK_PROGRESS+"-"+taskId), "processedQuantity", 1);
            // 记录处理明细
            Map<String, String> processedData = new HashMap<>();
            processedData.put("jhOriginalUrl", productsOnSale.getJhOriginalUrl());
            processedData.put("jhExplain", productsOnSale.getJhExplain());
            // 2. 序列化为JSON
            String jsonData="";
            try {
                jsonData = objectMapper.writeValueAsString(processedData);
            } catch (Exception e) {
                log.error("序列化错误", e);
            }
            redisCache.setCachePush((CacheConstants.TASK_INFO+"-"+taskId), jsonData);
        }
        return CompletableFuture.completedFuture(productsOnSales);
    }

}
